<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Home extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }
        }

    }
    /**
     * location 自动定位返回id：location
     * $location  地区名称
     */
    public function locationGet (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取轮播图
     * $type:1是首页  2是任务（分类）
     */
    public function getBanner(){
        extract(input());
        $data = Db::name('lunbo')
            ->where('lunbo_type','in',"$type,3")
            ->where('lunbo_status',1)
            ->field(['lunbo_id','lunbo_image','lunbo_task_id'])
            ->order('lunbo_update_time DESC')
            ->page (1,5)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }


    /**
     * 获取首页数据:getTasks
     */
    public function getTasks(){
        extract(input());
        //--------------------纯粹是为了排序，把进行中的未领完的放上面 start -----------------------------------------------------
        $change2 = Db::table('up_task')
            ->where('task_order',1)
            ->where('task_status',2)
            ->where('task_active_status',2)
            ->where('task_active','in','1,2')
            ->field('task_id,task_num,task_get_num')
            ->select();
        $ids2 = array();
        if($change2){
            foreach ($change2 as $k=>$v){
                if($v['task_num'] == $v['task_get_num']){
                    $ids2[] = $v['task_id'];
                }
            }
        }
        Db::table('up_task')
            ->where('task_order',1)
            ->where('task_status','>',2)
            ->setField('task_order',2);
        if($ids2){
            Db::table('up_task')
                ->where('task_id','in',$ids2)
                ->setField('task_order',2);
        }
        //--------------------纯粹是为了排序，把进行中的未领完的放上面 end -----------------------------------------------------
//        -------------------------------------------
        if(isset($user_sheng)){
            $sssll = ['user_province'=>$user_sheng,'user_city'=>$user_shi,'user_district'=>$user_qu];
            if(isset($s_lon) && isset($s_lat)){
                $sssll['user_lat'] = $s_lat;
                $sssll['user_lon'] = $s_lon;
            }
            Db::table('up_u_user')->where('user_id',$user_id)->update($sssll);
        }
//        -------------------------------------------
        $nosids = Db::name('shops')->where('s_sta',2)->column('s_id');
        $where = array();
        if($nosids){
            //不能是冻结的商家的
            $where['task_s_id'] = array('not in',$nosids);
        }
//        $where['task_status'] = array('in','1,2,3,4');
        $where['task_status'] = array('in','2,3,4');
        $where['task_active_status'] = 2;
        $where['task_active'] = ['in','1,2']; // 不展示达人任务
        if(isset($active) && $active == 1){
            $where['task_active'] = 2;
        }
        $order = 'task_order ASC,task_status ASC,task_time DESC';
        //1-1、首页数据展示（必须推荐，且按照推荐时间倒叙排）
        if(isset($index) && $index == 1){
            $where['task_index'] = 2;
            $order = 'task_index_time DESC';
        }
        //1-2、搜索数据展示（搜索的是所有的任务，不是只搜首页的）
        if(isset($search) && $search){
            $where['task_name'] = array('like','%'.$search.'%');
        }
        //2-1、某个分类下的
        if(isset($type) && $type > 0){
            $where['task_type'] = $type;
        }
        //2-2、奖励排序
        if(isset($price) && $price > 0){//1是从小到大
            if($price == 1){
                $order = 'task_price ASC,task_order ASC,task_status ASC,task_time DESC';
            }else{
                $order = 'task_price DESC,task_order ASC,task_status ASC,task_time DESC';
            }
        }
        //2-3、余量排序
        if(isset($number) && $number > 0){//1是从小到大
            if($number == 1){
                $order = 'task_num_have ASC,task_order ASC,task_time DESC';//和奖励相反，因为task_done_num是已领数量
            }else{
                $order = 'task_num_have DESC,task_order ASC,task_time DESC';
            }
        }
        $field = 'task_id,task_name,task_image,task_num,task_price,task_get_num,task_status,task_type';
        $field .= ',task_starttime,task_endtime';
        $field .= ",task_num - task_get_num as task_num_have";
        $field .= ",task_active";
        //3、云同城
        if(isset($same) && $same == 1){
            $data = Db::name('task')
                ->where(function ($query) {
                    $query->where('task_status', 'in','1,2,3,4')->where('task_active_status', 2)->where('task_sheng', 0);
                })
                ->whereOr(function ($query) use($qu) {
                    $query->where('task_status', 'in','1,2,3,4')->where('task_active_status', 2)->where('task_qu', 'like','%'.$qu.'%');
                })
                ->field($field)
                ->order($order)
                ->page($page,10)
                ->select();
        }else{
            $data = Db::name('task')
                ->where($where)
                ->field($field)
                ->order($order)
                ->page($page,10)
                ->select();
        }
        $datas = $this->handleTaskData($data,$user_id);
        //获取滚动的那20条消息
        $gun_news = Db::table('up_gun_news')
            ->order('gun_time DESC')
            ->page(1,20)
            ->select();
        return json(['status'=>200,'msg'=>$datas,'gun_news'=>$gun_news]);
    }

    protected function handleTaskData($data,$user_id)
    {
        //1是未开始  2是进行中  3是已结束 4是已下架
        if($data){
            foreach ($data as $k=>$v){
                $have = Db::table('up_task_user')
                    ->where('tu_task_id',$v['task_id'])
                    ->where('tu_user_id',$user_id)
                    ->field('tu_status')
                    ->find();
                if($v['task_status'] == 2 && $v['task_get_num'] >= $v['task_num']){
                    $data[$k]['task_status'] = 5;//已领完
                }
                if($have){
                    if($have['tu_status'] == 2 && $v['task_status'] == 2){
                        $data[$k]['task_status'] = 6;//已完成
                    }
                }
            }
        }
        return $data;
    }

    //--------------------------------详情和领取--------------------------------
    /**
     * H5的分享页获取任务详情
     */
    public function getH5TaskInfo(){
        extract(input());
        $tu_task_id = Db::name('task_user')->where('tu_id',$task_id)->value('tu_task_id');
        $where = array();
        $where['task_id'] = $tu_task_id;
        //1、任务详情
        $data = Db::name('task t')
            ->join('shops s','t.task_s_id=s.s_id','LEFT')
            ->where($where)
            ->field('t.*,s_id,s_name,s_thumb,s_image')
            ->find();
        if($data['task_type'] == 6 && $data['task_share_type'] == 2){
            Db::name('task')->where($where)->setInc('task_share_click');
            //到达率的话统计下当前的这个有多少人点
            Db::name('task_user')->where('tu_id',$task_id)->setInc('tu_share_b_num');
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取任务详情
     */
    public function getTaskInfo(){
        extract(input());
        $where = array();
        $where['task_id'] = $task_id;
        //1、任务详情
        $data = Db::name('task t')
            ->join('shops s','t.task_s_id=s.s_id','LEFT')
            ->where($where)
            ->field('t.*,s_id,s_name,s_thumb,s_image')
            ->find();
//        --------------任务不在进行了start
        if($data['task_status'] == 5){
            return json(['status'=>0,'msg'=>'任务已被删除！']);
        }
//        if($data['task_status'] != 2){
//            return json(['status'=>0,'msg'=>'任务不在进行中']);
//        }
//        --------------任务不在进行了 end
        //2、我有没有点赞(1是未点赞 2是已点赞)
        $zan = 1;
        $havezan = Db::table('up_task_zan')
            ->where('tz_task_id',$task_id)
            ->where('tz_user_id',$user_id)
            ->field('tz_id')
            ->find();
        if($havezan){
            $zan = 2;
        }
        //3、我可不可以领取(123456)
        $have = Db::table('up_task_user')
            ->where('tu_task_id',$task_id)
            ->where('tu_user_id',$user_id)
            ->find();
        if($data['task_get_num'] >= $data['task_num'] && $data['task_status'] == 2){
            $data['task_status'] = 5;//已领完
        }
        if($have){
            if($have['tu_status'] == 2 && $data['task_status'] == 2){
                $data['task_status'] = 6;//已完成
            }
        }
        return json(['status'=>200,'msg'=>$data,'zan'=>$zan]);
    }
    /**
     * 领取任务
     */
    public function receiveTask(){
        extract(input());
        //=-=-=-=-=-=-=-=-=-没有绑定手机号，只能领一个=-=-=-=-=-=-=-=-=
        $have_bd = Db::table('up_task_user')
            ->where('tu_user_id',$user_id)
            ->find();
        if($have_bd){
            $user_bd = Db::table('up_u_user')->where('user_id',$user_id)
                ->field('user_phone')
                ->find();
            if(empty($user_bd['user_phone'])){
                return json(['status'=>108,'msg'=>'您不能再领，请去绑定手机号~']);
            }
        }
        //=-=-=-=-=-=-=-=-=-end=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $where = array();
        $where['task_id'] = $task_id;
        //1、任务详情
        $data = Db::name('task')
            ->where($where)
            ->field('task_get_num,task_num,task_status,task_sheng,task_qu,task_type,task_active,task_share_d_fen')
            ->find();
        if($data){
            if(isset($qu) && $qu > 0){
                if($data['task_sheng'] != 0){
                    $qustr = ',' . $data['task_qu'] . ',';
                    if(!strstr($qustr,",$qu,")){
                        return json(['status'=>0,'msg'=>'您不在此任务领取范围内']);
                    }
                }
            }else{
                return json(['status'=>0,'msg'=>'没有定位信息，无法领取']);
            }
            if($data['task_status'] != 2){
                return json(['status'=>0,'msg'=>'此任务已下架或者已结束，不可领取']);
            }elseif ($data['task_get_num'] >= $data['task_num']){
                return json(['status'=>0,'msg'=>'此任务已被领完']);
            }else{
                $can = Db::name('task_user tu')//是不是有进行中的任务
                    ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
                    ->where('tu_user_id',$user_id)
                    ->where('tu_task_active',$data['task_active']) //同类型的可以个领一个
                    ->where('task_status','in','2,3')
                    ->column('tu_status');
                if($data['task_share_d_fen'] == 1){
                    if(in_array(3,$can) || in_array(4,$can)){
                        return json(['status'=>0,'msg'=>'进行中已经有任务啦，去完成~']);
                    }
                }else{
                    $can_5 = Db::name('task_user tu')//是不是有进行中的任务
                    ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
                        ->where('tu_user_id',$user_id)
                        ->where('task_share_d_fen',2)
                        ->where('task_status','in','2,3')
                        ->where('tu_status','in','3,4')
                        ->group('tu_task_id')
                        ->count();
                    if($can_5 >= 5){
                        return json(['status'=>0,'msg'=>'分步骤任务进行中不能超过5个，请先去完成~']);
                    }
                }
//                if(in_array(3,$can) || in_array(4,$can)){
//                    return json(['status'=>0,'msg'=>'进行中已经有任务啦，去完成~']);
//                }else{
                    $today = date('Y-m-d H:i:s');
                    $have = Db::table('up_task_user')
                        ->where('tu_task_id',$task_id)
                        ->where('tu_user_id',$user_id)
                        ->order('tu_share_fen DESC')
                        ->find();
                    if($have){
                        $tu_id = $have['tu_id'];
                        if($have['tu_status'] == 6 || $have['tu_status'] == 7){
                            if($have['tu_share_fen'] > 1){
                                return json(['status'=>0,'msg'=>'此任务您不能再领了~']);
                            }
                            $update = array();
                            $update['tu_image'] = '';
                            $update['tu_receive_time'] = $today;
                            $update['tu_submit_time'] = '';
                            $update['tu_cancel_time'] = '';
                            $update['tu_do_time'] = '';
                            $update['tu_reason'] = '';
                            $update['tu_status'] = 4;
                            $update['tu_real_time'] = $today;
                            $update['tu_have_not'] = 1;
                            $update['tu_del'] = 1;
                            //大富要的
                            $update['tu_date'] = date('Y-m-d');
                            $update['tu_hour'] = date('Y-m-d H');
                            $res = Db::table('up_task_user')
                                ->where('tu_task_id',$task_id)
                                ->where('tu_user_id',$user_id)
                                ->update($update);
                        }else{
                            return json(['status'=>0,'msg'=>'此任务还在进行中或者您已完成~']);
                        }
                    }else{
//                        tu_hour,tu_type,tu_date
                        //可以领取：
                        $sid = Db::table('up_task')->where('task_id',$task_id)->value('task_s_id');
                        $insert = array();
                        $insert['tu_number'] = time() . rand(10,99);
                        $insert['tu_task_id'] = $task_id;
                        $insert['tu_s_id'] = $sid;
                        $insert['tu_user_id'] = $user_id;
                        $insert['tu_image'] = '';
                        $insert['tu_receive_time'] = $today;
                        $insert['tu_submit_time'] = '';
                        $insert['tu_cancel_time'] = '';
                        $insert['tu_do_time'] = '';
                        $insert['tu_reason'] = '';
                        $insert['tu_status'] = 4;
                        $insert['tu_real_time'] = $today;
                        //大富要的
                        $insert['tu_date'] = date('Y-m-d');
                        $insert['tu_hour'] = date('Y-m-d H');
                        $insert['tu_type'] = $data['task_type'];
                        $insert['tu_task_active'] = $data['task_active'];
                        $res = Db::table('up_task_user')->insertGetId($insert);
                        $tu_id = $res;
                    }
                    if($res){
                        //领取任务量加1
                        Db::table('up_task')->where('task_id',$task_id)->setInc('task_get_num');
                        return json(['status'=>200,'msg'=>'领取成功','tu_id'=>$tu_id]);
                    }else{
                        return json(['status'=>0,'msg'=>'领取失败']);
                    }
//                }

            }
        }else{
            return json(['status'=>0,'msg'=>'已经没有此任务了']);
        }
    }

    /**
     * 点赞和取消点赞
     */
    public function taskZan()
    {
        extract(input());
        // 启动事务
        Db::startTrans();
        try{
            $res = Db::table('up_task_zan')
                ->where('tz_task_id',$task_id)
                ->where('tz_user_id',$user_id)
                ->find();
            if($res){
                Db::table('up_task_zan')
                    ->where('tz_task_id',$task_id)
                    ->where('tz_user_id',$user_id)
                    ->delete();
               Db::table('up_task')->where('task_id',$task_id)->setDec('task_zan');

            }else{
                Db::table('up_task_zan')->insert(['tz_task_id'=>$task_id,'tz_user_id'=>$user_id]);
                Db::table('up_task')->where('task_id',$task_id)->setInc('task_zan');
                //-----首次达到对应赞数要给商户发消息 S -----
                $task = Db::table('up_task')
                    ->where('task_id',$task_id)
                    ->field('task_zan,task_bai_zan,task_wubai_zan,task_qian_zan,task_name,task_s_id')
                    ->find();
                if($task['task_zan'] >= 100 && $task['task_bai_zan'] == 1){
                    Db::table('up_task')->where('task_id',$task_id)->setInc('task_bai_zan');
                    allInNotice('点赞','您发布的'.$task['task_name'].'任务，点赞量超过100啦~',3,$task['task_s_id']);
                }
                if($task['task_zan'] >= 500 && $task['task_wubai_zan'] == 1){
                    Db::table('up_task')->where('task_id',$task_id)->setInc('task_wubai_zan');
                    allInNotice('点赞','您发布的'.$task['task_name'].'任务，点赞量超过500啦~',3,$task['task_s_id']);
                }
                if($task['task_zan'] >= 1000 && $task['task_qian_zan'] == 1){
                    Db::table('up_task')->where('task_id',$task_id)->setInc('task_qian_zan');
                    allInNotice('点赞','您发布的'.$task['task_name'].'任务，点赞量超过1000啦~',3,$task['task_s_id']);
                }
                //-----首次达到对应赞数要给商户发消息 E -----
            }
            //========================
            // 提交事务
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'成功']);
            //=====end===============
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }

    //---------------------------------达人和排行榜--------------------------------------------
    /**
     * 达人列表
     */
    public function getSuperList(){
        extract(input());
        $where = array();
        $where['sup_status'] = 2;
        if(isset($keyword) && $keyword != ''){
            $where['sup_name'] = ['like',"%" . $keyword . "%"];
        }
        //1、列表
        $data = Db::table('up_super s')
            ->where($where)
            ->order('sup_rz_time DESC')
            ->page($page,10)
            ->field('sup_id,sup_name,photo,sup_goods')
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 达人详情
     */
    public function getSuperInfo(){
        extract(input());
        $where = array();
        $where['sup_id'] = $sup_id;
        //1、详情
        $data = Db::table('up_super s')
            ->where($where)
            ->find();
        if($data['sup_image']){
            $data['sup_image'] = explode(',',$data['sup_image']);
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 排行榜
     */
    public function getTopUsers(){
        extract(input());
        $where = array();
        $where['user_status'] = 1;
        if(!isset($type)){
            $type = 1;
        }
        if($type == 1){
            $where['user_week_money'] = array('>',0);
            $order = 'user_week_money';
        }else{
            $where['user_month_money'] = array('>',0);
            $order = 'user_month_money';
        }

        //1、排行列表
        $data = Db::table('up_u_user')
            ->where($where)
            ->order("$order DESC")
            ->page($page,15)
            ->field("user_id,user_username,user_image,$order as money")
            ->select();
        //2、我的排行
        $subQuery = Db::table("(SELECT @rownum := 0) r,up_u_user t")
            ->field (['user_id,user_username','user_image',"$order as money","@rownum := @rownum + 1"=>"rownum"])
            ->order ("$order desc")
            ->buildSql();
        $user = Db::table ($subQuery.' b')
            ->where(['b.user_id'=>$user_id])
            ->field (['user_username','user_image',"money",'b.rownum'])
            ->find ();
        if($user['money'] <= 0){
            $user['rownum'] = '暂未上榜';
        }
        return json(['status'=>200,'msg'=>$data,'user'=>$user]);
    }
}